package main;

//Lembrete: fazer printingVisitor como classe interna

import iterator.Iterator;

import java.util.NoSuchElementException;

import visitor.Visitor;
import wrapper.Comparable;

import container.AbstractContainer;
import container.ContainerEmptyException;
import container.ContainerFullException;
import container.Stack;
import enumeration.Enumeration;

public class StackAsArray extends AbstractContainer implements Stack{
	protected Object[] array;
	
	public StackAsArray(int size)
	{
		array = new Object[size];
	}
	
	public void push(Object object)
	{
		if(count == array.length)
			try {
				throw new ContainerFullException();
			} catch (ContainerFullException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			array[count++] = object;
	}
	
	public Object pop()
	{
		if(count == 0)
			try {
				throw new ContainerEmptyException("Pilha vazia");
			} catch (ContainerEmptyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		Object result = array[--count];
		array[count] = null;
		return result;	
	}
	
	public Object getTop()
	{
		if(count == 0)
			try {
				throw new ContainerEmptyException();
			} catch (ContainerEmptyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return array[count-1];
	}

	public void accept(Visitor visitor) {
		for(int i = 0; i < count; ++i)
		{
			visitor.visit(array[i]);
			if(visitor.isDone())
				return;
		}
	}

	public Enumeration getEnumeration() {
		return new Enumeration()
		{
			protected int position = 0;
			
			public boolean hasMoreElements()
			{
				return position < getCount();
			}
			public Object nextElement()
			{
				if(position >= getCount())
					throw new NoSuchElementException("Elemento não encontrado");
				return array[position++];
			}
		};
	}
	
	public Iterator getIterator()
	{
		return new Iterator()
		{
			protected int position;
			
			public void init()
			{
				position = 0;
			}
			
			public boolean test()
			{
				return position < getCount();
			}
			
			public void inc()
			{
				position++;
			}
			
			public Object current()
			{
				return array[position];
			}
		};
	}

	public void purge() {
		while(count > 0)
			array[--count] = null;
	}

	@Override
	protected int compareTo(Comparable arg0) {
		// TODO Auto-generated method stub
		return 0;
	}



}
